package duyd.ws.training.service.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import duyd.ws.training.domain.Contact;
import duyd.ws.training.service.ContactService;

@Service("contactService")
@Transactional
@Repository
public class ContactServiceImpl implements ContactService {

	@PersistenceContext
	EntityManager entityManager;

	private Log log = LogFactory.getLog(ContactServiceImpl.class);

	@Transactional(readOnly = true)
	public List<Contact> findAll() {
		return entityManager.createNamedQuery("contact.findAll", Contact.class)
				.getResultList();
	}

	@Transactional(readOnly = true)
	public List<Contact> findAllWithDetail() {
		return entityManager.createNamedQuery("contact.findAllWithDetail",
				Contact.class).getResultList();
	}

	@Transactional(readOnly = true)
	public Contact findById(Long id) {
		return entityManager
				.createNamedQuery("contact.findById", Contact.class)
				.setParameter("id", id).getSingleResult();
	}

	public Contact save(Contact contact) {
		if (contact.getId() == null) {
			entityManager.persist(contact);
			log.info("New contact inserted: " + contact);
		} else {
			entityManager.merge(contact);
			log.info("Existing contact updated: " + contact);
		}
		return contact;
	}

	public void delete(Contact contact) {
		Contact managedContact = entityManager.merge(contact);
		entityManager.remove(managedContact);
		log.info("Contact removed: " + contact);
	}
}
